<script setup>
import EZUIKit from "ezuikit-js";
import { onMounted } from "vue";
import { get, post } from '@/utils/request'
import { ElMessage } from 'element-plus';

let player;

const emit = defineEmits(['capture-success'])

const play = () => {
  const playPromise = player.play();
  playPromise.then((data) => {
    console.log("promise 获取 数据", data);
    ElMessage.success('播放成功');
  }).catch(error => {
    console.error('播放失败:', error);
    ElMessage.error('播放失败，请重试');
  });
};

const stop = () => {
  try {
    const stopPromise = player.stop();
    stopPromise.then((data) => {
      console.log("promise 获取 数据", data);
      // code 31 是正常的停止状态
      if (data && data.code === 31) {
        ElMessage.success('停止成功');
      } else {
        ElMessage.success('停止成功');
      }
    }).catch(error => {
      console.error('停止失败:', error);
      ElMessage.error('停止失败，请重试');
    });
  } catch (error) {
    console.error('停止出错:', error);
    ElMessage.error('停止出错，请重试');
  }
};

const getOSDTime = () => {
  const getOSDTimePromise = player.getOSDTime();
  getOSDTimePromise.then((data) => {
    console.log("promise 获取 数据", data);
  });
};

const capturePicture = async () => {
  try {
    const accessToken = await getToken();
    const response = await post('/api/ys/capture', {
      accessToken,
      deviceSerial: 'L29334649',
      channelNo: 1,
      quality: 1
    });
    
    if (response && response.picUrl) {
      ElMessage.success('抓拍成功');
      emit('capture-success', {
        picUrl: response.picUrl,
        time: response.time || new Date().toLocaleString()
      });
    } else {
      ElMessage.error('抓拍失败: 未获取到图片地址');
    }
  } catch (error) {
    console.error('抓拍出错:', error);
    ElMessage.error('抓拍出错，请重试');
  }
};

const openSound = () => {
  const openSoundPromise = player.openSound();
  openSoundPromise.then((data) => {
    console.log("promise 获取 数据", data);
  });
};

const closeSound = () => {
  const openSoundPromise = player.closeSound();
  openSoundPromise.then((data) => {
    console.log("promise 获取 数据", data);
  });
};

const startSave = () => {
  const startSavePromise = player.startSave(`${new Date().getTime()}`);
  startSavePromise.then((data) => {
    console.log("promise 获取 数据", data);
  });
};

const stopSave = () => {
  const stopSavePromise = player.stopSave();
  stopSavePromise.then((data) => {
    console.log("promise 获取 数据", data);
  });
};

const ezopenStartTalk = () => {
  player.startTalk();
};

const ezopenStopTalk = () => {
  player.stopTalk();
};

const fullScreen = () => {
  player.fullScreen();
};

const destroy = () => {
  const destroyPromise = player.destroy();
  destroyPromise.then((data) => {
    console.log("promise 获取 数据", data);
  });
  player = null;
};

const getToken = async () => {
  try {
    // 先从 localStorage 获取 token
    const storedToken = localStorage.getItem('ys_token');
    const storedExpireTime = localStorage.getItem('ys_token_expire');
    
    // 如果有token且未过期，直接返回
    if (storedToken && storedExpireTime && Date.now() < parseInt(storedExpireTime)) {
      return storedToken;
    }

    // token不存在或已过期，重新请求
    const response = await get('/api/ys/token');
    const { accessToken, expireTime } = response;
    
    // 存储token和过期时间
    localStorage.setItem('ys_token', accessToken);
    localStorage.setItem('ys_token_expire', expireTime);
    
    return accessToken;
  } catch (error) {
    console.error('Error getting token:', error);
    throw error;
  }
};

// 确保DOM元素存在后再初始化
onMounted(() => {
  // 添加一个小延迟确保DOM已经渲染
  setTimeout(() => {
    init();
  }, 100);
});

const init = async () => {
  if (player) {
    destroy();
  }
  
  const container = document.getElementById('video-container');
  if (!container) {
    console.error('Video container not found');
    return;
  }
  
  try {
    const accessToken = await getToken();
    
    player = new EZUIKit.EZUIKitPlayer({
      id: "video-container",
      accessToken: accessToken,
      url: "ezopen://open.ys7.com/L29334649/1.hd.live",
      template: "simple",
      plugin: ["talk"],
      autoplay: true,
      handleError: async (err) => {
        console.error("handleError", err);
        // 如果是token过期错误,清除本地存储并重新初始化
        if (err.code === 401) {
          localStorage.removeItem('ys_token');
          localStorage.removeItem('ys_token_expire');
          init();
        }
      },
      env: {
        domain: "https://open.ys7.com"
      }
    });
    window.player = player;
  } catch (error) {
    console.error('Failed to initialize player:', error);
    ElMessage.error('播放器初始化失败，请刷新页面重试');
  }
};
</script>

<template>
  <div class="hello-ezuikit-js">
    <div id="video-container" class="video-container"></div>
    <div class="control-buttons">
      <button @click="stop">停止</button>
      <button @click="play">开始</button>
      <button @click="capturePicture">拍照</button>
    </div>
  </div>
</template>

<style scoped>
.hello-ezuikit-js {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.video-container {
  flex: 1;
  min-height: 300px;
}

:deep(.hello-ezuikit-js) {
  width: 100%;
  height: 100%;
}

#video-container {
  width: 100% !important;
  height: 100% !important;
  display: flex;
}


.control-buttons {
  margin-top: 8px;
  display: flex;
  justify-content: center;
  gap: 20px;

  button {
    background: rgba(3, 211, 236, 0.1);
    border: 1px solid #03d3ec;
    color: #fff;
    padding: 6px 20px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    
    &:hover {
      background: rgba(3, 211, 236, 0.2);
    }
    
    &:active {
      transform: scale(0.98);
    }
  }
}
</style>
